/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.snail.task;

import com.snail.cfg.XLogger;
import com.snail.beans.CmdResult;
import com.snail.main.XTask;
import it.sauronsoftware.cron4j.TaskExecutionContext;
import org.jsoup.nodes.Element;

/**
 *
 * @author pm
 */
public class ProcessTask extends XTask {

    public ProcessTask(Element full_cfg, Element cfg, Element module) {
        super(full_cfg, cfg, module);
    }

    @Override
    public void onExecute(TaskExecutionContext tec) throws RuntimeException {
        if (cfg.select(">flag").size() > 0) {
            String grep = cfg.attr("grep"), col = null;
            String rule = cfg.select(">success>flag").first().attr("rule");

            switch (rule) {
                case "mem":
                    col = "4";
                    break;
                case "cpu":
                    col = "3";
                    break;
                case "rss":
                    col = "6";
                    break;
            }
            if (col != null) {
                float max = Float.parseFloat(cfg.select(">success>flag").first().attr("max"));
                CmdResult result = getCol(grep, col);
                if (result.isSuccess()) {
                    float real = parseResult(result);
                    if (real > max) {
                        onError("1", String.valueOf(real));
                    } else {
                        onSuccess(String.valueOf(real));
                    }
                } else {
                    onError("2", "0");
                }
            } else {
                XLogger.logger.warn("unknown process rule : " + rule);
            }

        }
    }

    /**
     *
     * @param grep
     * @param col mem:4 cpu:3 rss:6
     * @return
     */
    private static CmdResult getCol(String grep, String col) {
        CmdResult result = exec("ps aux|grep -v grep|grep \"" + grep + "\"|awk '{print $" + col + "}'", 3000);
        if (result.getOutput().isEmpty()) {
            result.setSuccess(false);
        }
        return result;
    }

    private static float parseResult(CmdResult result) {
        String mems[] = result.getOutput().split("\\n");
        float total = 0;
        for (String v : mems) {
            try {
                total = total + Float.parseFloat(v);
            } catch (NumberFormatException e) {
            }
        }
        return total;
    }

}
